package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    IUserService userService;
    @Resource
    IBlogService blogService;
    @Resource
    BlogMapper blogMapper;

    /**
     * 关注 和 取关
     */
    @Override
    @Transactional
    public Result follow(Long followId, Boolean type) {
        // 1 获取userId
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail("用户未登录！");
        }
        Long userId = user.getId();
        // 2 判断是type 关注 还是 取关
        // 粉丝列表key
        String fansKey = BLOG_FOLLOW_KEY + followId;
        // 关注列表key
        String subkey = BLOG_SUB_KEY + userId;
        String feedKey = BLOG_FEED_KEY + userId;
        if(type){
            // 3 关注
            // 3.1 添加到tb_follow表
            Follow follow = new Follow();
            follow.setFollowUserId(followId);
            follow.setUserId(userId);
            boolean isSaved = save(follow);
            if(isSaved){
                // 3.2 粉丝列表--把userId存到ZSET里，方便后续判断是否关注
                stringRedisTemplate.opsForZSet().add(fansKey, userId.toString(), System.currentTimeMillis());
                // 3.3 关注列表--把followId存到ZSET里，方便后续判断是否关注
                stringRedisTemplate.opsForZSet().add(subkey, followId.toString(), System.currentTimeMillis());
                // 3.4 feed  关注时将博主的文章推送到user的收件箱
                List<Long> idList = blogMapper.getIdByUserId(followId);
                idList.forEach(id ->{
                    stringRedisTemplate.opsForZSet().add(feedKey, id.toString(), System.currentTimeMillis());
                });

            }
        }else{
            // 4 取关
            // 4.1 从tb_follow表中删除相关数据
            QueryWrapper<Follow> wrapper = new QueryWrapper<>();
            boolean isRemoved = remove(wrapper.eq("user_id", userId).eq("follow_user_id", followId));
            if(isRemoved){
                // 4.2 粉丝列表--从ZSET中remove userId
                stringRedisTemplate.opsForZSet().remove(fansKey, userId.toString());
                // 4.3 关注列表--从ZSET中remove followId
                stringRedisTemplate.opsForZSet().remove(subkey, followId.toString());
                // 4.4 feed列表--从ZSET中remove
                // 然后查询取关博主的发表笔记的id，从redis的feed中删除id
                List<String> ids = blogMapper.getIdByUserId(followId)
                        .stream().map(Object::toString).collect(Collectors.toList());
                ids.forEach(id -> stringRedisTemplate.opsForZSet().remove(feedKey, id));
            }
        }
        return Result.ok();
    }

    /**
     * 判断用户是否关注博主
     */
    @Override
    public Result isFollowed(Long followId) {
        // 1 获取当前用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail("您还没有登录~");
        }
        // 2 查看当前用户id是否在redis的zset中存贮
        String key = BLOG_FOLLOW_KEY + followId;
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        return Result.ok(score != null);
    }

    @Override
    public Result commonSub(Long blogerId) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail("您还没有登录~");
        }
        String userkey = BLOG_SUB_KEY + user.getId();
        String blogerkey = BLOG_SUB_KEY + blogerId;
        String tempKey = "temp:zset:inter:" + UUID.randomUUID();
        // 查set集合交集
        try {
            stringRedisTemplate.opsForZSet().intersectAndStore(userkey, blogerkey, tempKey);
            Set<String> interSet = stringRedisTemplate.opsForZSet().range(tempKey, 0, -1);
            if(interSet == null || interSet.isEmpty()){
                return Result.ok();
            }
            List<Long> ids = interSet.stream().map(Long::valueOf).collect(Collectors.toList());
            List<UserDTO> userDTOList = userService.listByIds(ids)
                    .stream()
                    .map(u -> BeanUtil.copyProperties(u, UserDTO.class))
                    .collect(Collectors.toList());
            return Result.ok(userDTOList);
        } finally {
            stringRedisTemplate.delete(tempKey);
        }
    }
}
